﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'edit_cards_logic.dart';
import 'edit_cards_state.dart';

/// 编辑卡片页面
class EditCardsView extends GetView<EditCardsLogic> {
  const EditCardsView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF282528),
      appBar: AppBar(
        title: const Text(
          '编辑卡片',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        elevation: 0,
        backgroundColor: const Color(0xFF282528),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Get.back(),
        ),
        actions: [
          TextButton(
            onPressed: controller.saveCardConfiguration,
            child: Text(
              '保存',
              style: TextStyle(
                color: const Color(0xffED5C2F),
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: EdgeInsets.all(20.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 说明文字
              Container(
                padding: EdgeInsets.all(16.w),
                decoration: BoxDecoration(
                  color: const Color(0xFF2A2A2A),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Row(
                  children: [
                    Icon(
                      Icons.info_outline,
                      color: const Color(0xffED5C2F),
                      size: 20.sp,
                    ),
                    SizedBox(width: 12.w),
                    Expanded(
                      child: Text(
                        '仅可编辑"卡片数据"模块中的小卡片',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Colors.grey[300],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 20.h),
              // 显示在首页部分
              _buildDisplayedSection(),
              SizedBox(height: 30.h),
              // 不显示在首页部分
              _buildHiddenSection(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建显示在首页部分
  Widget _buildDisplayedSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '显示在卡片数据中',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        SizedBox(height: 8.h),
        Text(
          '长按拖动调整卡片顺序，拖到下方区域可隐藏',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[400],
          ),
        ),
        SizedBox(height: 16.h),
        Obx(() {
          if (controller.state.displayedCards.isEmpty) {
            return Container(
              height: 100.h,
              child: Center(
                child: Text(
                  '暂无显示的卡片',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[500],
                  ),
                ),
              ),
            );
          }

          return ReorderableListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: controller.state.displayedCards.length,
            onReorder: (oldIndex, newIndex) {
              final List<HealthCardItem> items =
                  List.from(controller.state.displayedCards);
              if (oldIndex < newIndex) {
                newIndex -= 1;
              }
              final HealthCardItem item = items.removeAt(oldIndex);
              items.insert(newIndex, item);
              controller.updateDisplayedOrder(items);
            },
            itemBuilder: (context, index) {
              final card = controller.state.displayedCards[index];
              return _buildReorderableCard(card, index);
            },
          );
        }),
      ],
    );
  }

  /// 构建不显示在首页部分
  Widget _buildHiddenSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '不显示在卡片数据中',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        SizedBox(height: 8.h),
        Text(
          '将上方卡片拖到此处可隐藏，点击隐藏的卡片可恢复显示',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[400],
          ),
        ),
        SizedBox(height: 16.h),
        // 使用DragTarget接收拖拽
        DragTarget<HealthCardItem>(
          onWillAcceptWithDetails: (details) => details.data.isDisplayed,
          onAcceptWithDetails: (details) {
            controller.moveCardToHidden(details.data);
          },
          builder: (context, candidateData, rejectedData) {
            final isHovering = candidateData.isNotEmpty;
            return Obx(() {
              if (controller.state.hiddenCards.isEmpty && !isHovering) {
                return _buildEmptyHiddenArea(isHovering);
              }
              return Container(
                decoration: BoxDecoration(
                  border: isHovering
                      ? Border.all(
                          color: const Color(0xffED5C2F),
                          width: 2.0,
                        )
                      : null,
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Column(
                  children: controller.state.hiddenCards.map((card) {
                    return Padding(
                      padding: EdgeInsets.only(bottom: 8.h),
                      child: _buildCardItem(card, -1, isDisplayed: false),
                    );
                  }).toList(),
                ),
              );
            });
          },
        ),
      ],
    );
  }

  /// 构建空白的隐藏区域
  Widget _buildEmptyHiddenArea(bool isHovering) {
    return Container(
      width: double.infinity,
      height: 120.h,
      decoration: BoxDecoration(
        border: Border.all(
          color: isHovering ? const Color(0xffED5C2F) : Colors.grey[600]!,
          width: isHovering ? 2.0 : 1.0,
          style: BorderStyle.solid,
        ),
        borderRadius: BorderRadius.circular(8.r),
        color: isHovering
            ? const Color(0xffED5C2F).withOpacity(0.1)
            : Colors.transparent,
      ),
      child: Center(
        child: Text(
          isHovering ? '松手隐藏卡片' : '将卡片拖到此处可隐藏',
          style: TextStyle(
            fontSize: 14.sp,
            color: isHovering ? const Color(0xffED5C2F) : Colors.grey[500],
            fontWeight: isHovering ? FontWeight.w500 : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  /// 构建可重排序的卡片（用于显示列表）
  Widget _buildReorderableCard(HealthCardItem card, int index) {
    return Container(
      key: ValueKey(card.id),
      margin: EdgeInsets.only(bottom: 8.h),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(
          color: const Color(0xFF3A3A3A),
          width: 1.0,
        ),
      ),
      child: Row(
        children: [
          // 图标
          Container(
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: const Color(0xffED5C2F).withOpacity(0.2),
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Center(
              child: Icon(
                _getIconForCard(card.id),
                color: const Color(0xffED5C2F),
                size: 20.sp,
              ),
            ),
          ),
          SizedBox(width: 12.w),
          // 标题
          Expanded(
            child: Text(
              card.title,
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.white,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          // 隐藏按钮
          IconButton(
            icon: Icon(
              Icons.visibility_off,
              color: Colors.grey[400],
              size: 20.sp,
            ),
            onPressed: () => controller.moveCardToHidden(card),
            padding: EdgeInsets.zero,
            constraints: const BoxConstraints(),
          ),
          SizedBox(width: 8.w),
          // 拖拽手柄
          Icon(
            Icons.drag_handle,
            color: Colors.grey[400],
            size: 20.sp,
          ),
        ],
      ),
    );
  }

  /// 构建卡片项目
  Widget _buildCardItem(HealthCardItem card, int index,
      {required bool isDisplayed}) {
    final cardWidget = Container(
      key: ValueKey(card.id),
      margin: EdgeInsets.only(bottom: 8.h),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(
          color: const Color(0xFF3A3A3A),
          width: 1.0,
        ),
      ),
      child: Row(
        children: [
          // 图标
          Container(
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: const Color(0xffED5C2F).withOpacity(0.2),
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Center(
              child: Icon(
                _getIconForCard(card.id),
                color: const Color(0xffED5C2F),
                size: 20.sp,
              ),
            ),
          ),
          SizedBox(width: 12.w),
          // 标题
          Expanded(
            child: Text(
              card.title,
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.white,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          // 拖拽手柄（仅显示列表）
          if (isDisplayed)
            Icon(
              Icons.drag_handle,
              color: Colors.grey[400],
              size: 20.sp,
            ),
        ],
      ),
    );

    // 隐藏列表的卡片可以点击恢复显示
    if (!isDisplayed) {
      return GestureDetector(
        onTap: () => controller.moveCardToDisplayed(card),
        child: cardWidget,
      );
    }

    return cardWidget;
  }

  /// 根据卡片ID获取图标
  IconData _getIconForCard(String cardId) {
    switch (cardId) {
      case 'health_dashboard':
        return Icons.dashboard;
      case 'vital_metrics':
        return Icons.monitor_heart;
      case 'diet_record':
        return Icons.restaurant;
      case 'emotion_management':
        return Icons.sentiment_satisfied;
      case 'stress':
        return Icons.self_improvement;
      case 'daily_events':
        return Icons.event_note;
      case 'heart_rate':
        return Icons.favorite;
      case 'hrv':
        return Icons.show_chart;
      case 'sleep':
        return Icons.bedtime;
      case 'blood_oxygen':
        return Icons.water_drop;
      case 'activity':
        return Icons.directions_run;
      case 'workout_records':
        return Icons.timer;
      case 'physiological_cycle':
        return Icons.calendar_today;
      default:
        return Icons.health_and_safety;
    }
  }
}
